<template>
  <el-dialog
    v-el-drag-dialog
    :title="type==='bottle' ? '瓶批单结单' : '槽批单结单'"
    :visible.sync="visible"
    width="1024px"
    @closed="reset"
  >
    <el-form ref="dataForm" class="form" :model="temp" label-position="right" label-width="120px">
      <el-form-item label="单号:" prop="orderCode">
        <el-input v-model="temp.orderCode" disabled />
      </el-form-item>
      <el-form-item label="责任机构:" prop="orgName">
        <el-input v-model="temp.orgName" disabled />
      </el-form-item>
      <el-form-item label="批发类型:" prop="wsaleType">
        <el-input v-model="wsaleType" disabled />
      </el-form-item>
      <el-form-item label="支付方式:" prop="paymentMethod">
        <el-input v-model="paymentMethod" disabled />
      </el-form-item>
      <el-form-item label="客户:" prop="csmName">
        <el-input v-model="temp.csmName" disabled />
      </el-form-item>
      <el-form-item label="电话:" prop="contactPhone">
        <el-input v-model="temp.contactPhone" disabled />
      </el-form-item>
      <el-form-item label="地址:" prop="csmAddress">
        <el-input v-model="temp.csmAddress" disabled />
      </el-form-item>
      <el-form-item v-if="type==='lorry'" label="商品:" prop="goodsName">
        <el-input v-model="goodsName" disabled />
      </el-form-item>
      <el-form-item v-if="type==='lorry'" label="单价(元/吨):" prop="gPrice">
        <el-input v-model="gPrice" disabled />
      </el-form-item>
      <el-form-item v-if="type==='lorry'" label="灌装费:" prop="totalFee1">
        <el-input v-model="totalFee1" disabled />
      </el-form-item>
      <el-form-item v-if="type==='lorry'" label="空车重(吨):" prop="weight1">
        <el-input v-model="weight1" disabled />
      </el-form-item>
      <el-form-item v-if="type==='lorry'" label="重车重(吨):" prop="weight2">
        <el-input v-model="weight2" disabled />
      </el-form-item>
      <el-form-item v-if="type==='lorry'" label="实收净重(吨):" prop="totalNetWeight">
        <el-input-number v-if="isInfo ===''" v-model="totalNetWeight" :controls="false" :min="-99999" :max="99999" :precision="5" placeholder="请输入" style="width: 100%;" @change="setTotal(3)" />
        <el-input-number v-else v-model="totalNetWeight" placeholder="请输入" :controls="false" :min="-99999" :max="99999" :precision="5" style="width: 100%;" @change="setTotal(3)" />
      </el-form-item>
      <el-form-item v-if="type==='lorry'" label="盈余量(吨):" prop="weight3">
        <el-input v-model="weight3" disabled />
      </el-form-item>
      <el-form-item label="配送车辆:" prop="truckNo">
        <el-input v-model="temp.truckNo" disabled />
      </el-form-item>
      <el-form-item v-show="temp.wsaleType === 3" label="运费单价(元/吨):" prop="freightPrice">
        <el-input v-model="temp.freightPrice" disabled />
      </el-form-item>
      <el-form-item label="总运费:" prop="decimalSpare1">
        <el-input v-model="decimalSpare1" disabled />
      </el-form-item>
      <el-form-item v-if="type==='bottle'" label="司机:" prop="driver">
        <el-input v-model="temp.driver" disabled />
      </el-form-item>
      <el-form-item v-if="type==='bottle'" label="押送员:" prop="escortName">
        <el-input v-model="temp.escortName" disabled />
      </el-form-item>
      <el-form-item label="备注:" prop="remark" class="block">
        <el-input v-if="type==='lorry'" v-model="remark" type="textarea" :rows="3" maxlength="255" show-word-limit />
        <el-input v-else v-model="remark" type="textarea" :rows="3" maxlength="255" show-word-limit disabled />
      </el-form-item>
      <el-form-item label="应收金额:" class="block">
        {{ type === 'bottle' ? goodsSum + temp.decimalSpare1 : totalMoney }}
      </el-form-item>
    </el-form>
    <lb-table
      v-if="type==='bottle'"
      ref="lbTable"
      border
      element-loading-text="加载中"
      :column="tableData.column"
      :data="tableData.data"
      :summary-method="getSummaries"
      show-summary
      highlight-current-row
    />
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">
        取消
      </el-button>
      <el-button v-if="isInfo ===''" type="primary" @click="openToPay">
        结单
      </el-button>
    </div>
    <to-pay ref="toPay" />
  </el-dialog>
</template>

<script>
  import { queryWsaleOrderBillDetail, saveLorryOrderAccount } from '@/api'
  import { accDiv, keepDotLength } from '@/utils/math'
  import ToPay from './ToPay'

  export default {
    name: 'statement-bottle',
    components: {
      ToPay
    },
    data() {
      return {
        visible: false,
        type: 'bottle',
        totalNetWeight: undefined,
        isInfo: '',
        remark: '',
        wsaleTypeBottleMap: [{ 'value': 1, 'desc': '预约批发', 'key': 'TYPE1' }, { 'value': 2, 'desc': '上门批发', 'key': 'TYPE2' }],
        temp: {
          wsaleType: '',
          decimalSpare1: 0
        },
        totalMoney: 0,
        goodsSum: 0,
        tableData: {
          data: [],
          column: [
            {
              prop: 'goodsName',
              label: '商品'
            },
            {
              prop: 'specName',
              label: '规格型号'
            },
            {
              prop: 'gCount',
              label: '数量',
              align: 'right'
            },
            {
              prop: 'gdWeight',
              label: '每瓶重量(kg)',
              align: 'right',
              render: (h, { row }) => row.gdWeight && <span>{ accDiv(row.gdWeight).toFixed(2) }</span>
            },
            {
              prop: 'netWeight',
              label: '总重量(吨)',
              align: 'right',
              render: (h, { row }) => <span>{ row.netWeight }</span>
            },
            {
              prop: 'gPrice',
              label: '单价',
              align: 'right'
            },
            {
              prop: 'tReceivable',
              label: '金额',
              align: 'right',
              render: (h, { row }) => row.tReceivable && <span>{ row.tReceivable.toFixed(2) }</span>
            }
          ]
        }
      }
    },
    computed: {
      wsaleType: function() {
        const obj = {
          1: '预约批发',
          2: '上门批发',
          3: '代运业务'
        }
        return obj[this.temp.wsaleType]
      },
      paymentMethod: function() {
        const obj = {
          0: '',
          1: '现金',
          2: '微信支付',
          16: '月结',
          128: '支付宝',
          256: '预付卡',
          512: '国志钱包',
          1024: '银行支付'
        }
        return obj[this.temp.paymentMethod]
      },
      goodsName: function() {
        return this.temp.orderWsaleOrderDetailInfoList.length ? this.temp.orderWsaleOrderDetailInfoList[0].goodsName : ' '
      },
      gPrice: function() {
        return this.temp.orderWsaleOrderDetailInfoList.length ? (this.temp.orderWsaleOrderDetailInfoList[0].gPrice).toFixed(2) : ' '
      },
      totalFee1: function() {
        return this.temp.totalFee1.toFixed(2)
      },
      weight1: function() {
        return (this.temp.weight1 / 1000).toFixed(5)
      },
      weight2: function() {
        return this.temp.weight2 ? (this.temp.weight2 / 1000).toFixed(5) : '0.00000'
      },
      weight3: function() {
        return this.temp.weight3 === 0 ? '0.00000' : (this.temp.weight3 / 1000).toFixed(5)
      },
      decimalSpare1: function() {
        return this.temp.decimalSpare1 === 0 ? '0.00' : this.temp.decimalSpare1.toFixed(2)
      }
    },
    methods: {
      setTotal(type) {
        switch (type) {
        case 3:
        {
          if (this.temp.wsaleType === 3) {
            this.temp.decimalSpare1 = this.totalNetWeight * this.temp.freightPrice
          }
          const value3 = keepDotLength(this.gPrice, 2) * keepDotLength(this.totalNetWeight, 5) + keepDotLength(this.totalFee1, 2) + keepDotLength(this.decimalSpare1, 2)
          this.totalMoney = value3.toFixed(2)
          // this.temp.weight1 = 0
          // this.temp.weight2 = 0
          this.temp.weight3 = (this.weight2 - this.weight1 - (keepDotLength(this.totalNetWeight, 5)).toFixed(5)) * 1000
          break
        }
        }
      },
      async open(temp, type, isInfo) {
        const res = await queryWsaleOrderBillDetail({
          orderCode: temp.orderCode
        })
        this.temp = res.data
        this.remark = ''
        if (res.data.totalNetWeight || res.data.totalNetWeight === 0) {
          this.$set(this, 'totalNetWeight', keepDotLength(res.data.totalNetWeight / 1000, 5).toFixed(5))
        }
        if (this.temp.remark) {
          this.remark = this.temp.remark
        }
        this.tableData.data = res.data.orderWsaleOrderDetailInfoList
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
          this.type = type
          this.isInfo = isInfo || ''
          if (type !== 'bottle') {
            const value3 = keepDotLength(this.gPrice, 2) * keepDotLength(this.totalNetWeight, 5) + keepDotLength(this.totalFee1, 2) + keepDotLength(this.decimalSpare1, 2)
            this.totalMoney = value3.toFixed(2)
          }
        })
      },
      // 合计方法
      getSummaries(param) {
        const { columns, data } = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '合计'
            return
          }
          if (column.property === 'gdWeight' || column.property === 'gPrice') {
            return
          }
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
          }
        })
        if (sums.length > 5) {
          this.goodsSum = sums[6]
        }
        return sums
      },
      async openToPay() {
        if (this.type === 'lorry') {
          const res = await saveLorryOrderAccount({
            totalNetWeight: (this.totalNetWeight * 1000).toFixed(2),
            orderCode: this.temp.orderCode,
            weight3: (this.temp.weight3).toFixed(2),
            tReceivables: this.totalMoney,
            decimalSpare1: this.decimalSpare1,
            remark: this.remark
          })
          if (res) { this.visible = false }
          this.$refs.toPay.open(this.temp, this.totalMoney)
        } else {
          this.visible = false
          this.$refs.toPay.open(this.temp, this.goodsSum + this.temp.decimalSpare1)
        }
      },
      onInput(value) {
        const res = value
          .replace(/[^\d.]/g, '')
          .replace(/\.{2,}/g, '.')
          .replace(/^\./g, '')
          .replace('.', '$#$')
          .replace(/\./g, '')
          .replace('$#$', '.')
          .replace(/^0\d+|^\./g, '')
          .replace(/^(.*\..{2}).*$/, '$1')
        this.totalNetWeight = res
        if (this.isInfo === '') {
          this.temp.weight3 = ((this.totalNetWeight * 1) - (this.totalNetWeight * 2 - 1)) * 1000
          this.temp.tReceivables = (this.totalNetWeight * 6200) + 34
        } else {
          this.temp.weight3 = ((this.temp.totalNetWeight / 1000) - this.totalNetWeight * 1) * 1000
          this.temp.tReceivables = (this.totalNetWeight * 6200)
        }
      },
      async formatInput(e) {
        if (e.target.value) {
          this.totalNetWeight = (e.target.value * 1).toFixed(5)
        }
      },
      reset() {
        this.type = 'bottle'
        this.totalNetWeight = undefined
        this.temp = {
          wsaleType: '',
          decimalSpare1: 0
        }
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  flex-wrap: wrap;
  & /deep/ .el-form-item {
    width: 33.3%;
    padding-right: 10px;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
  .block {
    width: 100%;
  }
}
</style>
